package com.ruubypay.biz.mvc.workflow.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruubypay.biz.mvc.workflow.model.request.CandidateUser;
import com.ruubypay.biz.mvc.workflow.model.request.ProcessInstanceVO;
import com.ruubypay.biz.mvc.workflow.model.response.AuditProcessResponse;
import com.ruubypay.biz.mvc.workflow.service.RuntimeProcessService;
import com.ruubypay.web.common.code.ResultCode;
import com.ruubypay.web.common.code.ResultEntity;
import com.ruubypay.web.common.page.DataGrid;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 运行中的流程控制器
 * @author chenhaiyang
 */
@Controller
@RequestMapping(value="/workflow/runtimeprocess/")
public class RuntimeProcessController {

    private static Logger logger = LoggerFactory.getLogger(RuntimeProcessController.class);
    @Resource
    private RuntimeProcessService runtimeProcessService;

    /**
     * 列表页跳转
     * @return 返回url
     */
    @RequestMapping(value = "/list" , method = RequestMethod.GET)
    public String listModels() {
        return "views/runtimeprocess/process_list";
    }

    /**
     * 根据执行id获取当前流程的所有审批过程和流程执行图片
     * @param request request 请求类
     * @return 返回流程相关的信息
     */
    @RequestMapping(value = "/processinfo" , method = RequestMethod.GET)
    public ModelAndView processinfo(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("views/runtimeprocess/process_detail");

        try {
            String excuseId = request.getParameter("excuseId");
            List<AuditProcessResponse> historicActivityInstanceList = runtimeProcessService.histoicFlowList(excuseId);
            mv.addObject("historyActivitiLists",historicActivityInstanceList);
            String imgSrc = runtimeProcessService.getNowTaskPng(excuseId);
            mv.addObject("imgSrc",imgSrc);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return mv;
    }

    /**
     * 获取运行中的流程列表
     * @return 流程
     */
    @ResponseBody
    @RequestMapping(value="/list",method = RequestMethod.POST)
    public String list(HttpServletRequest request) {
        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put("name",request.getParameter("name"));
        paramMap.put("businessKey",request.getParameter("businessKey"));
        Integer pageNumber = ServletRequestUtils.getIntParameter(request,"pageNumber",1);
        Integer pageSize = ServletRequestUtils.getIntParameter(request,"pageSize",10);

        DataGrid modelPage = null;
        try {
            modelPage = runtimeProcessService.listDataRuntimeProcesses(paramMap,pageNumber,pageSize);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return JSON.toJSONString(modelPage);
    }

    /**
     * 对运行中对流程执行挂起
     * @return 返回操作结果
     */
    @ResponseBody
    @RequestMapping(value="/onoff",method = RequestMethod.POST)
    public String onoff(ProcessInstanceVO processInstanceVO){
        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        if (StringUtils.isNotBlank(processInstanceVO.getProcessInstanceId())&&
                Arrays.asList(1,2).contains(processInstanceVO.getIsSuspended())) {
            try {
                runtimeProcessService.suspendedOrNo(processInstanceVO);
            } catch (Exception e) {
                resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_SERVER_DATABASE);
                logger.error(e.getMessage(),e);
            }
            return JSONObject.toJSONString(resultEntity);
        }
        resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_CLIENT_PARAMETER_NUll);
        return JSONObject.toJSONString(resultEntity);
    }

    /**
     * 对运行中对流程执行作废
     * @return 返回操作结果
     */
    @ResponseBody
    @RequestMapping(value="/delete",method = RequestMethod.POST)
    public String delete(ProcessInstanceVO processInstanceVO){
        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        if (StringUtils.isNotBlank(processInstanceVO.getProcessInstanceId())&&
                StringUtils.isNotBlank(processInstanceVO.getReason())) {
            try {
                runtimeProcessService.deleteProcessInstance(processInstanceVO);
            } catch (Exception e) {
                resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_SERVER_DATABASE);
                logger.error(e.getMessage(),e);
            }
            return JSONObject.toJSONString(resultEntity);
        }
        resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_CLIENT_PARAMETER_NUll);
        return JSONObject.toJSONString(resultEntity);
    }

    /**
     * 对运行中的流程重新分类候选人
     * @return 返回操作结果
     */
    @ResponseBody
    @RequestMapping(value="/candidateUser",method = RequestMethod.POST)
    public String candidateUser(CandidateUser candidateUser){
        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        if (StringUtils.isNotBlank(candidateUser.getExcusedId())&&
                StringUtils.isNotBlank(candidateUser.getUsers())) {
            try {
                runtimeProcessService.candidateUser(candidateUser);
            } catch (Exception e) {
                resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_SERVER_DATABASE);
                logger.error(e.getMessage(),e);
            }
            return JSONObject.toJSONString(resultEntity);
        }
        resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_CLIENT_PARAMETER_NUll);
        return JSONObject.toJSONString(resultEntity);
    }


}
